package legumes.server.usl.services;

import java.util.Enumeration;

import javax.servlet.http.HttpSession;

import legumes.server.bll.BLLLegumesServicesImpl;
import legumes.shared.domain.Customer;
import legumes.shared.domain.CustomerDTO;
import legumes.shared.domain.SellSession;

import org.jBCrypt.BCrypt;

import com.google.appengine.api.datastore.QueryResultIterator;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.Objectify;

public class AbstractRemoteServiceServlet extends RemoteServiceServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String CUSTOMER_DTO_IN_SESSION = "customer-dto";

	public boolean amILogged() {
		return getMyCustomerDTO() != null;
	}

	@Override
	protected void doUnexpectedFailure(Throwable e_) {
		e_.printStackTrace();

		// rollback eventual session
//		try {
//			Session session = HibernatePoint.getSessionFactory()
//					.getCurrentSession();
//			if (session.isOpen()) {
//				session.getTransaction().rollback();
//			}
//		} catch (HibernateException he_) {
//
//		}
//
//		super.doUnexpectedFailure(e_);
	}

	public boolean logMe(String login_, String password_) {
		Customer c = BLLLegumesServicesImpl.getInstance().getCustomerFromEmail(login_);
		if (c == null || (c != null && !c.isAccountActivated()) ) {
			return false;
		}

		boolean validPassword = BCrypt.checkpw(password_, c.getPassword());
		// Root password is good for all customers !
		//!Customer.SUPER_PASSWORD.equals(password_) && 
		if (!validPassword) {
			return false;
		}

		BLLLegumesServicesImpl.getInstance().onCustomerLogon(c, 
				getThreadLocalRequest().getRemoteHost());
		

		CustomerDTO cdto = new CustomerDTO(c);
		HttpSession httpSession = getThreadLocalRequest().getSession();
		httpSession.setAttribute(CUSTOMER_DTO_IN_SESSION, cdto);
		httpSession.setMaxInactiveInterval(30);
		
		return true;
	}

	protected CustomerDTO getMyCustomerDTO() {
		return (CustomerDTO) getThreadLocalRequest().getSession().getAttribute(CUSTOMER_DTO_IN_SESSION);
	}

	protected SellSession findLastSellSession(Objectify ofy_){
		SellSession ssMaxCreationDate = null;
		QueryResultIterator<SellSession> sellSessionIt = ofy_.query(SellSession.class).iterator();
		while( sellSessionIt.hasNext() ){
			SellSession ss = sellSessionIt.next();
			if( ssMaxCreationDate == null ||
					(ssMaxCreationDate != null &&
					ssMaxCreationDate.getCreationDate()< ss.getCreationDate()) ){
				ssMaxCreationDate = ss;
			}
		}
		
		return ssMaxCreationDate;
	}
	
	public void unlogMe() {
		HttpSession httpSession = getThreadLocalRequest().getSession();
		httpSession.invalidate();
	}

	public static String toString(HttpSession session_) {
		StringBuilder sb = new StringBuilder();

		sb.append("[HttpSession ").append(" id=").append(session_.getId())
				.append(" customerDTO=").append(
						session_.getAttribute(CUSTOMER_DTO_IN_SESSION)).append(
						"\nkeepAlive=").append(
						session_.getMaxInactiveInterval())

				.append(" attributes=\n");

		Enumeration e = session_.getAttributeNames();
		int i = 0;
		while (e.hasMoreElements()) {
			sb.append("\tattribute[").append(i).append("]=").append(
					e.nextElement()).append("\n");
		}
		sb.append("]");

		return sb.toString();
	}

}
